iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 23
0
自我挑戰組

純新手學習 JavaScript系列 第 23

新手學習JavaScript:day23 - Best Time to Buy and Sell Stock

  • 分享至 

  • xImage
  •  

直接來上今天的題目吧!

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

var maxProfit = function(prices) {
    let profit = []
   prices.forEach((price,index)=>{
     profit.push(Math.max(...(prices.slice(index + 1))) - price )
   })
    let maxProfit = Math.max(...profit)
    return maxProfit > 0? maxProfit : 0
};

今天的題目,會給一個數字陣列,那我們要找最大的獲利,注意選取的最小值一定要在最大值之前。

思考:
1.我們可以一次選取一個值,然後讓之後數列中的最大值去減它就能找到每一個數字的差。所以,我先宣告一個空陣列去紀錄每一次的差。

var maxProfit = function(prices) {
    let maxProfit;
    let profit = []
   prices.forEach((price,index)=>{
    let rest = prices.slice(index + 1)
    let num = Math.max(...rest) - price 
    profit.push(num)
   }
};
  1. 最後找出每一次差的的最大值就會是獲利最大的結果,但要注意如果是負值,我們就要回傳 0。
var maxProfit = function(prices) {
    let maxProfit;
    let profit = []
   prices.forEach((price,index)=>{
    let rest = prices.slice(index + 1)
    let num = Math.max(...rest) - price 
    profit.push(num)
   }
    maxProfit = Math.max(...profit)
    return maxProfit > 0? maxProfit : 0
};

以上就是今天的刷題挑戰,以上解法效能非常慢,寫法上有非常大的進步空間。如果有哪位大大路過經過,還請多多賜教。


上一篇
新手學習JavaScript:day22 - Two Sum
下一篇
新手學習JavaScript:day24 - Contains Duplicate
系列文
純新手學習 JavaScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
janshawn
iT邦新手 5 級 ‧ 2020-10-08 14:38:59
// 解一(效能較差)
var maxProfit = function (prices) {
    var profit = 0;
    prices.forEach((price, index) => {
        prices.forEach((p, i) => {
            if (i > index) profit = (p - price > profit) ? p - price : profit;
        });
    })
    return profit;
};

//解二(效能較優,朋友解)
var maxProfit = function (pricesArr) {
    var max = 0;
    pricesArr.forEach((price, index) => {
        for (let j = index + 1; j < pricesArr.length; j++) {
            if (pricesArr[j] - price > max) max = pricesArr[j] - price;
        }
    })
    return max;
};

我要留言

立即登入留言